# -*- coding:Utf-8 -*-
'''
Created on 25 nov. 2012

@author: fefoley
'''

import calendar, datetime

from workday import WorkDay
import myio, myalgo


"""tmp comment"""


def _wddico_init(str_start, str_end):
    """init a dictionary of days, from startday to endday included"""
    startday = datetime.datetime.strptime(str_start, "%d/%m/%Y")
    endday = datetime.datetime.strptime(str_end, "%d/%m/%Y")
    startyear = startday.year
    endyear = endday.year
    
    wddico = {}
    for y in range(startyear, endyear+1):
        nb_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
        if calendar.isleap(y): nb_days[1] = 29
        
        'must be complete months for the given years, with empty workday if out of range(startday, endday)'
        'empty wddico'
        wddico[y] = [[[] for d in range(0,nb_days[m])] for m in range(0,12)]
    
    'set the workdays'
    for y in wddico.keys():
        nb_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
        if calendar.isleap(y): nb_days[1] = 29        
   
        for m in range(0,12):
            for d in range(0, nb_days[m]):
                if datetime.datetime(y, m+1, d+1) >= startday \
                   and datetime.datetime(y, m+1, d+1) <= endday:
                    wddico[y][m][d] = WorkDay(datetime.date(y, m+1, d+1))
        
#        wddico[y] = [[WorkDay(datetime.date(y, j+1, i+1)) for i in range(0,nb_days[j])] \
#                      for j in range(0,12)]        
    return wddico

def _wddico_getday(wddico, adate):
    """proc to return the corresponding WorkDay to a given datetime.date"""
    y = adate.year
    m = adate.month
    d = adate.day
    if y in wddico: return wddico[y][m-1][d-1]
    return []


#########################################################

if __name__ == "__main__":
 
    # file constantes - could be automated using an explorer to choose file
    input_root_path = "/home/test-dev/reverse_hours.io/"
    path_to_configfile = input_root_path + "reverse_hours.config.txt"
        
    "importation des paramètres de config"
    config = myio.import_config(path_to_configfile)
    
    "importation des données dans des listes"
    lstmails = myio.import_mails(config) # importer la liste des mails et retourne une liste d'objet Mail
    lstmeetings = myio.import_meetings(config) # importer la liste des réunions et retourne une liste d'objet Meeting
    lstsentmeetings = myio.import_sentmeetings(config) # importer la liste des réunions et retourne une liste d'objet Meeting
    lstholidays = myio.import_holidays(config) # importer la liste des jours fériés et retourne une liste d'objet datetime.date
    lstdaysoff = myio.import_daysoff(config) # importer la liste des congés et retourne une liste d'objet datetime.date
    
    'create the dictionary entry of the years'
    wdstart = config.get('workday','startday')
    wdend = config.get('workday','endday')
    wddico = _wddico_init(wdstart, wdend)
    
    'add mails'
    for mail in lstmails:
        wd = _wddico_getday(wddico, mail.getsentdatetime())
        if wd: wd.addmail(mail)
    
    'add meetings' 
    # Commencer avec pre-processing des meetings --> avoir des meetings uniquement à l'intérieur d'une journée  ??
    lstmeetings = myalgo.preprocess_meeting(lstmeetings)
    for meeting in lstmeetings: 
        'add the meeting to the day it is happening'
        wd = _wddico_getday(wddico, meeting.getdatetime())         
        if wd: wd.addmeeting(meeting)   

    'add sentmeetings' 
    for sentmeeting in lstsentmeetings: 
        'add the sent meeting to the day it was sent if I sent it'
        wd = _wddico_getday(wddico, sentmeeting.getsentdatetime())         
        if wd: wd.addsentmeeting(sentmeeting)   

    'add holidays'
    for (holiday_date, holiday_name) in lstholidays:    #holiday = (date, name)
        wd = _wddico_getday(wddico, holiday_date)
        if wd: wd.setholiday(holiday_name)
    
    'add dayoffs'
    for (start, end, strtype, nbday) in lstdaysoff:     #dayoff = (startdate, enddate, typedayoff, length)
        "loop from start to end with +1day"
        if start > end:  # check start > end, otherwise could have endless loop
            raise Exception("FromDate > ToDate in dayoffs data!")
        while start <= end:
            "find the WorkDay set the dayoff to it"
            wd = _wddico_getday(wddico, start)
            if wd: wd.setdayoff(strtype)
            start += datetime.timedelta(days=1)

    
    'lets do something here'  
    
    
    'création des TimeStrip'
    for key, year in wddico.items():
        for month in year:
            for wday in month:
                if wday:
                    wday.compute_timestrips()
                    wday.aggreg_timestrips()     #aggrégation ds TimeStrip

        
    #Optimisation des TimesStrip
    

    """
    impression des TimeStrip  pour import dans Excel
    YYYY/MM/DD    tsStart    tsEnd    encoded_Label
    """
    lst_lst_timestrip =[]
    for key, year in wddico.items():
        for month in year:
            for wday in month:
                if wday: lst_lst_timestrip.append(wday.timestrips_on)
                    
    myio.output_timestrip(lst_lst_timestrip, config)

    """
    Debug timestrip OFF
    YYYY/MM/DD    tsStart    tsEnd    encoded_Label
    """
    lst_lst_timestrip =[]
    for key, year in wddico.items():
        for month in year:
            for wday in month:
                if wday: lst_lst_timestrip.append(wday.timestrips_off)
    str_debug = ""
    for lst_timestrip in lst_lst_timestrip:
        for ts in lst_timestrip:
            line = ts.start.strftime("%Y/%m/%d") + '\t' + ts.start.strftime("%H:%M") \
                                                 + '\t' + ts.end.strftime("%H:%M") \
                                                 + '\t' + ts.label.replace('\t','\\utab').replace('\n','\\ueol') \
                                                 + '\n'
            str_debug  = str_debug + line
                               
    myio.debug_output(str_debug, config)

    